using System;
using System.Collections;
using System.Collections.Generic;
using QFramework;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.UI;

//积分manager的作用：
//1.记录个人赛积分池
//2.记录班级赛积分池
//3.记录点赞积分进入积分池
//4.记录送礼积分进入积分池
//5.计算个人赛单人积分
//6.计算班级赛 班级积分
// 个人赛积分计算规则
//答对一题+100分，打错一题+20分，未答题不加分不扣分
//班级赛积分规则
//答对一题+100分，打错一题+20分，未答题不加分不扣分

//点赞进入积分池，一次点赞计入1分

//送礼计入积分池，一个抖币计100分。累加
public enum JiFen{
    rightAnswer = 100,//答对 100分
    wrongAnswer = 20,//答错 20分
    zan = 1,//点赞加1分
    gift = 10,//送礼加10*抖币分(10倍)
}
public class JifenManager : MonoBehaviour
{
   
    public Text JiFenPoolText; // 积分池节点

    private int JiFenPoolNum = 0; // 积分池的数值

    public Text ClassAJifenPoolText = null; //班级A的积分节点
    private int ClassAJifenPoolNum = 0;

    public Text ClassBJifenPoolText = null; //班级B的积分节点
    private int ClassBJifenPoolNum = 0;

    private StudentManager studentManager;

    //列表第一位表示被挑战者，第二位表示挑战者，在积分结算的时候会进行对比
    private List<GameObject> TiaoZhanNo1List = new List<GameObject>(); 

    private int JueDiFanJiEnable = 0; // 0表示没有绝地反击，1表示classA的绝地反击，2表示classB的绝地反击
    private List<int> SingleTiClassJiFen = new List<int> { 0, 0 }; //绝地反击开始后，记录AB班级的积分，第一位是A班的积分，第二位是B班级的积分
     
    void Start()
    {
        // 如果没有指定StudentManager，则尝试查找
        if (studentManager == null)
        {
            studentManager = FindObjectOfType<StudentManager>();
            if (studentManager == null)
            {
                UnityEngine.Debug.LogWarning("GiftManager: StudentManager not assigned or found!");
            }
        }
        StringEventSystem.Global.Register(EventID.SingleJifenJieSuanStart, (List<GameObject> studentsNodes) =>
            {
                HandleSingleJifen(studentsNodes);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);

         StringEventSystem.Global.Register(EventID.ClassJifenJieSuanStart, (List<GameObject> studentsNodes) =>
            {
                HandleClassJifen(studentsNodes);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);

        UpdateJiFenPool();
        if(PlayerPrefs.GetString(GameMode.Mode) == GameMode.Tuandui){
            UpdateClassAJifenPool();
            UpdateClassBJifenPool();
        }
        

        //监听点赞数据
        StringEventSystem.Global.Register(EventID.DianZan, (int zanNum) =>
            {
                AddJiFenPool(zanNum * (int)JiFen.zan);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
        //监听送礼数据
        StringEventSystem.Global.Register(EventID.GiftJifen, (int giftNum) =>
            {
                Debug.Log("礼物增加积分池："+ giftNum * (int)JiFen.gift);
                AddJiFenPool(giftNum * (int)JiFen.gift);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);

        //监听挑战第一名
        StringEventSystem.Global.Register(EventID.GiftSingleTiaoZhanNo1,(GameObject studentNode)=>
            {
                //将挑战者和被挑战者 放在一个新的列表TiaoZhanNo1List中
                TiaoZhanNo1(studentNode);
            }).UnRegisterWhenGameObjectDestroyed(gameObject);
        //绝地反击
        StringEventSystem.Global.Register(EventID.GiftClassJueDiFanJi, (GameObject studentsNode) =>
        {
            JueDiFanJi(studentsNode);
        }).UnRegisterWhenGameObjectDestroyed(gameObject);
    }

    private void HandleSingleJifen(List<GameObject> studentsNodes)
    {
        
        RefreshJifenByStudentNodes(studentsNodes);
        //判断挑战者
        if(TiaoZhanNo1List.Count == 0){
            //没有挑战
            StringEventSystem.Global.Send(EventID.SingleModeJifenOver, studentsNodes);
            return;
        }else{
            //判断挑战者的答案是不是对，当且仅当 第一名回答错误，挑战者回答正确，才获得积分
            int rightAnswer = PlayerPrefs.GetInt(GameMode.correctAnswer);
            GameObject Top1 = GetTop1();
            if(rightAnswer != 0 && Top1 != null){
                //第一名回答错误
                if(Top1.GetComponentInChildren<Student>().answer != rightAnswer){
                    //挑战者回答正确
                    int temp = Top1.GetComponentInChildren<Student>().getJifen(); 
                    foreach(var st in TiaoZhanNo1List){
                         if(st.GetComponentInChildren<Student>().answer == rightAnswer){
                            st.GetComponentInChildren<Student>().SetSingleTiJifen(temp);
                         }
                    }
                     
                     TiaoZhanNo1List.Clear();
                }
            }
            StringEventSystem.Global.Send(EventID.SingleModeJifenOver, studentsNodes);
        }
       
    }

    private void HandleClassJifen(List<GameObject> studentsNodes)
    {
        RefreshJifenByStudentNodes(studentsNodes);

        if (JueDiFanJiEnable == 1 || JueDiFanJiEnable == 2)
        {
            // 判断哪个班级发起了绝地反击
            bool isClassA = JueDiFanJiEnable == 1; // A班发起的
            int currentClassScore = isClassA ? SingleTiClassJiFen[0] : SingleTiClassJiFen[1];
            int opponentClassScore = isClassA ? SingleTiClassJiFen[1] : SingleTiClassJiFen[0];

            // 判断当前班级的积分是否大于对方班级的积分
            if (currentClassScore > opponentClassScore)
            {
                // 反击成功
                Debug.Log($"{(isClassA ? "A班" : "B班")} 反击成功");

                // 交换双方的积分
                if (isClassA)
                {
                    // A班反击成功，交换 A 班和 B 班的积分
                    int tempScore = SingleTiClassJiFen[0];
                    SingleTiClassJiFen[0] = SingleTiClassJiFen[1];
                    SingleTiClassJiFen[1] = tempScore;

                    // 更新班级积分池
                    ClassAJifenPoolNum = SingleTiClassJiFen[0];
                    ClassBJifenPoolNum = SingleTiClassJiFen[1];
                }
                else
                {
                    // B班反击成功，交换 B 班和 A 班的积分
                    int tempScore = SingleTiClassJiFen[1];
                    SingleTiClassJiFen[1] = SingleTiClassJiFen[0];
                    SingleTiClassJiFen[0] = tempScore;

                    // 更新班级积分池
                    ClassAJifenPoolNum = SingleTiClassJiFen[0];
                    ClassBJifenPoolNum = SingleTiClassJiFen[1];
                }

                // 更新 UI 显示
                UpdateClassAJifenPool();
                UpdateClassBJifenPool();

                //清空状态
                SingleTiClassJiFen[0] = 0;
                SingleTiClassJiFen[1] = 0;
                JueDiFanJiEnable = 0;
            }
        }

        StringEventSystem.Global.Send(EventID.ClassJifenOver, studentsNodes);
    }

    //刷新积分的公共方法
    private void RefreshJifenByStudentNodes(List<GameObject> studentsNodes){
         int rightAnswer = PlayerPrefs.GetInt(GameMode.correctAnswer);
         foreach (var student in studentsNodes)
        {
            var st = student.GetComponentInChildren<Student>();
            var ClassType = st.getClassType();
            //获取学生答案
            var studentAnswer = st.answer;
            if(st.getChiTiZhengQue() == true){
                st.setAnswer(rightAnswer);
                studentAnswer = rightAnswer;
                Debug.Log("学生答案此题正确");
            }
            //比较学生答案与正确答案
            if (studentAnswer == rightAnswer)
            {
                int AddJiFenNum = (int)JiFen.rightAnswer * st.getBeishu();
                st.addJifen(AddJiFenNum);
                st.SetSingleTiJifen(AddJiFenNum);
                StringEventSystem.Global.Send(EventID.ShowAnswer, new string[] { "√", st.getStudentID() });
                AddJiFenPool(AddJiFenNum);
                if (ClassType == 1)
                {
                    AddClassAJifenPool(AddJiFenNum);
                }else if (ClassType == 2)
                {
                    AddClassBJifenPool(AddJiFenNum);
                }
            }else if (studentAnswer != 0)
            {
                int AddJiFenNum = (int)JiFen.wrongAnswer * student.GetComponentInChildren<Student>().getBeishu();
                student.GetComponentInChildren<Student>().addJifen(AddJiFenNum);
                student.GetComponentInChildren<Student>().SetSingleTiJifen(AddJiFenNum);
                AddJiFenPool(AddJiFenNum);
                if (ClassType == 1)
                {
                    AddClassAJifenPool(AddJiFenNum);
                }else if (ClassType == 2)
                {
                    AddClassBJifenPool(AddJiFenNum);
                }
            }
            
        }
    }

    //只有这里可以增加积分池，其他地方不允许修改
    private void AddJiFenPool(int jifen){

        JiFenPoolNum += jifen;
        UpdateJiFenPool();
    }

    public int GetJiFenPoolNum(){
        return JiFenPoolNum;
    }

    private void UpdateJiFenPool()
    {
        JiFenPoolText.text = JiFenPoolNum.ToString();
    }

    private void AddClassAJifenPool(int jifen){
        ClassAJifenPoolNum += jifen;
        UpdateClassAJifenPool();
        if(JueDiFanJiEnable == 1){
            SingleTiClassJiFen[0] += jifen;
        }
    }

    private void UpdateClassAJifenPool()
    {
        ClassAJifenPoolText.text = "积分："+ClassAJifenPoolNum.ToString();
    }

    private void AddClassBJifenPool(int jifen){
        ClassBJifenPoolNum += jifen;
        UpdateClassBJifenPool();
        if(JueDiFanJiEnable == 2){
            SingleTiClassJiFen[1] += jifen;
        }
    }

    private void UpdateClassBJifenPool()
    {
        ClassBJifenPoolText.text = ClassBJifenPoolNum.ToString() + "：积分";
    }

    private void TiaoZhanNo1(GameObject studentNode)
    {
        if (studentNode == null) return;
        TiaoZhanNo1List.Add(studentNode);
       
    }

    private void JueDiFanJi(GameObject studentNode){
        //先判断学生的班级类型
        int classType = studentNode.GetComponent<Student>().getClassType();
        //如果学生所在班级是优势方，则绝地反击无效
        if(classType == 1){
            if(ClassAJifenPoolNum > ClassBJifenPoolNum){
                Debug.Log("优势方无绝地反击");
                JueDiFanJiEnable =  0;
                return;
            }else{
                JueDiFanJiEnable = 1;
            }
        }else{
            if(ClassBJifenPoolNum > ClassAJifenPoolNum){
                Debug.Log("优势方无绝地反击");
                JueDiFanJiEnable =  0;
                return;
            }else{
                JueDiFanJiEnable = 2;
            }
        }
        
    }

    private GameObject GetTop1(){
        List<GameObject> studentsNodes = studentManager.GetAllStudents();
        GameObject topStudent = null;
        int highestScore = -1;

        // 遍历所有学生节点
        foreach (var student in studentsNodes)
        {
            int studentScore = student.GetComponentInChildren<Student>().getJifen();

                // 比较积分，找到最高的学生
                if (studentScore > highestScore)
                {
                    highestScore = studentScore;
                    topStudent = student; // 更新最高积分的学生
                }
        }

        // 处理找到的最高积分学生
        if (topStudent != null)
        {
            Debug.Log($"积分最高的学生是: {topStudent.name}，积分为: {highestScore}");
            
            return topStudent;
        }
        else
        {
            Debug.Log("没有找到学生或学生没有积分信息。");
            return null;
        }
    }
}
